// ----------------------------------------------------全局变量区-----------
var endFlag = false;
var readArticleCount;
var needReadArticleNum = 50;
var appPackageName = "com.app.yunli";
var storage = null;
var APP_NAME = "云里头条";
var rootAutomator = new RootAutomator();

// ----------------------------------------------------方法区-----------------------

Date.prototype.Format = function (fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};

/**
 * 
 * 通过bounds 点击
 * @param {*} btn  按钮对象
 */
function clickBtnByBoundsCenter(btn) {
    var position = btn.bounds();
    log("position" + position.centerX() + ":" + position.centerY());
    Tap(position.centerX(), position.centerY());
    sleep(1000);
}

/**
 * 判断是否主页
 */
function ifMainPage() {
    var flagBtn = desc("新手任务").findOne(3000);
    if (flagBtn) {
        return true;
    }
    return false;
}

/**
 * 判断是否阅读页面
 */
function ifReadPage() {
    var flagBtn = desc("推荐").findOne(5000);
    if (flagBtn) {
        return true;
    }
    return false;
}

/**
 * 是否登录
 */
function ifLogined() {
    sleep(2000);
    var userInfoBtn = desc("个人中心").findOne(3000);
    // toastLog(.bounds());
    if (userInfoBtn == null) {
        toastLog("未找到个人中心按钮");
        // return false;
    } else {
        sleep(1000);
        // 切换到个人中心
        clickBtnByBoundsCenter(userInfoBtn);
        sleep(1000);
        clickBtnByBoundsCenter(userInfoBtn);
        sleep(1000);

    }
    // 如果找不到今日收入，则未登录
    // var loginBtn = desc("登录").findOne(2000);
    var income = desc("今日收入").findOne(5000);
    if (!income) {
        // toastLog("未登录");
        return false;
    } else {
        toastLog("已登录");
    }
    return true;
}

/**
 * 模拟下拉,此函数可能出现下拉失灵的情况
 */
function simulateScorllDown() {
    // toastLog("下拉")
    sleep(2000);

    // var starx = random(500, 600);
    // var starty = device.height-100;
    // Swipe(starx, starty, starx , starty /2, random(400, 500));


    var starx = random(500, 600);
    var starty = random(600, 700);
    Swipe(starx, starty, starx, starty - device.height / 1.5, random(1000, 2000));
    sleep(500);
}

/**
 * 模拟下拉整个屏幕
 */
function simulateScorllDownFullScreen() {

    toastLog("下拉");
    sleep(2000);
    // var starx = random(500, 600);
    // var starty = device.height-100;
    // Swipe(starx, starty, starx , starty /2, random(400, 500));

    var starx = random(100, device.width - 100);
    var starty = device.height / 2 + 100;
    sleep(500);
    // toastLog(starty - (device.height/2));
    // Swipe(starx, starty, starx, starty-100,  2000);
    rootAutomator.swipe(starx, starty, starx, device.height / 1.5 - 100);
    // Swipe(200, 600, 200, 300,2000);
    sleep(500);

}

/**
 * 进入文章,需要修复
 */
function clickAnArticle() {
    // 文章列表
    var first = className("android.view.View").findOne(3000);
    if (first) {
        // toastLog("找到了");
        // clickBtnByBounds(first);
        sleep(2000);
        toastLog("点击文章");

        // 如果不在可视范围，则点击下一篇
        var clickY = first.bounds().centerY();
        if (first.bounds().centerY() < 100) {
            clickY = 300;
        }
        toastLog("Y轴" + clickY);
        Tap(100, clickY);
        sleep(2000);
    } else {
        // 这里有问题呀
        toastLog("未找到文章列表");
    }
}

/**
 * 通过bounds 进入文章
 */
function clickAnArticleByBounds(article) {
    toastLog("通过bounds 进入文章");

    if (article.parent()) {
        if (article.parent().childCount() > 1) {
            clickBtnByBoundsCenter(article.parent().child(1))
        }
    } else {
        var position = article.bounds();
        log("position" + position.centerX() + ":" + position.centerY());
        Tap(position.centerX() / 3, position.centerY() / 2);
    }
    sleep(1000);
}

/**
 * 完成一篇文章
 */
function finishReadAnArticle() {
    sleep(1000);
    var ifFinished = false;
    var ifArticleDetailPage = true;
    // 先判断是否在文章页面中
    var detailBtn = desc("任务详情").findOne(2000);
    if (!detailBtn) {
        toastLog("不在文章页");
        if (checkIfAdPage()) {
            back();
        }
        sleep(2000);
        if (!ifReadPage()) {
            switchToReadTabBar();
        }
        ifArticleDetailPage = false;
        return false;
    }

    // 获取文章标题

    var startTime = new Date();

    while (!ifFinished) {
        // if(new Date()-startTime >);
        sleep(3500);

        // 判断文章是否已经拉到底部
        var finishBtn = descStartsWith("阅读完成").findOne(2000);

        if (finishBtn == null) {
            toastLog("未找到阅读完成按钮");
            back();
            return false;
        }

        // 判断阅读完成 是否可见 ，小于阈值则不可见
        var ifNotVisible = !checkIfVisibleArticleItem(finishBtn.bounds())
        if (ifNotVisible) {
            toast("文章未到底");
            simulateScorllDown();
        } else {
            // 判断阅读完成倒计时是否结束
            var realFinishBtn = desc("阅读完成").findOne(2000);
            if (realFinishBtn) {
                toastLog("阅读完成")

                // 点击阅读完成两次
                clickBtnByBoundsCenter(realFinishBtn);
                sleep(1000);
                clickBtnByBoundsCenter(realFinishBtn);

                // 判断是否已获得奖励
                if (checkGetAward()) {
                    ifFinished = true;
                    sleep(1000);
                    toastLog("获得奖励");
                    // back();
                }
                return true;
            } else {
                toast("阅读倒计时未结束");
            }
        }
    }
    return;
}
function switchToReadTabBar() {
    // if (ifReadPage()) {
    //     return true;
    // }

    // var readPageBtn = desc("阅读").findOne(1000);
    // if (!readPageBtn) {
    //     toastLog("未找到阅读tabBar");
    //     if(checkIfAdPage()){
    //         back();
    //     }
    // }
    // sleep(1000);
    // clickBtnByBoundsCenter(readPageBtn);
    // sleep(1000);
    return true;
}
/**
 * 判断本次阅读是否已获得奖励
 */
function checkGetAward() {
    var realFinishBtn = desc("已获得金币").findOne(2000);
    return realFinishBtn != null;
    // toastLog("获得阅读奖励，返回");

}

function backToReadTabBar() {
    if (!ifReadPage()) {
        switchToReadTabBar();
    }

    // back();
    sleep(2000);
    if (!ifReadPage()) {
        switchToReadTabBar();
    }
}



/**
 * 将文章标题加入已阅读 列表
 */
function markReaded(title) {
    log("完成阅读文章" + title);
    storage.put(title, "");
}

/**
 * 初始化存储
 */
function initStorage() {
    var storageName = new Date().Format("yyyy-MM-dd") + appPackageName;
    storage = storages.create(storageName);

    if (storage == null) {
        toastLog("初始化本地存储失败");
        return false;
    }
    // toastLog("初始化本地存储成功");

}

/**
 * 判断文章今天是否阅读过
 * @param {文章标题} title 
 */
function checkIfReadedTody(title) {
    var ifReadedToday = storage.contains(title)
    log("检测：" + title + "  是否阅读过\n 结果" + ifReadedToday);
    return ifReadedToday;
}

/**
 * 获取今天未读过的文章列表
 * @param {文章列表} articleArray 
 */
function getUnReadedArticleArrayToday(articleArray) {
    var unReadedArticle = new Array();
    if (articleArray == undefined || articleArray == null || articleArray.length == 0) {
        return unReadedArticle;
    }

    for (var index = 0; index < articleArray.length; index++) {
        var element = articleArray[index];

        var title = element.desc() != null ? element.desc() : "";
        log("获取今天未读过的文章列表")
        if (!checkIfReadedTody(title)) {
            unReadedArticle.push(element);
        }
    }

    return unReadedArticle;
}

// ----------------------------------------------主方法区-------------------------------------------


/**
 * 判断是否在广告页面
 */
function checkIfAdPage() {
    var adTitle = id('com.app.yunli:id/title').findOne(3000);
    if (adTitle != null) {
        return true;
    }
    return false;
}

/**
 * 判断对象是否肉眼可见
 * @param {对象bounds} rect 
 */
function checkIsvisible(rect) {

    if (rect.centerX() < 0 && rect.centerX() > device.width) {
        return false;
    }
    if (rect.centerY() < 0 && rect.centerY() > device.height) {
        return false;
    }
    return true;
}

/**
 * 判断当前屏幕是否处于package内
 */
function checkIfInApp(packageName) {
    return currentPackage() == packageName;

}

/**
 * 退出app
 */
function exitAppByPackageName() {
    var result = shell("am force-stop " + appPackageName, true);
    sleep(500);
    return result.code == 0;
}

/**
 * 过滤当前栏 可见文章item
 */
function checkIfVisibleArticleItem(rect) {
    // 高一定是比宽大的
    var realHeight = device.height;
    var realWidth = device.width;

    if (realHeight < realWidth) {
        realHeight = device.width;
        realWidth = device.height;
    }

    if (rect.left > realWidth || rect.centerX < 0) {
        return false;
    }

    if (rect.bottom > realHeight || rect.bottom < 0) {
        return false;
    }

    // 顶部要比栏目高
    if (rect.top < 150) {
        return false;
    }
    return true;
}

/**
 * 
 */
function checkIfHeightAndWidthNormal() {
    if (device.height < device.width) {
        toastLog("错误的分辨率，宽应大于高！");
        // exit();
    }
}
/**
 * 重启app，并进入阅读页面（由于uniapp 的特殊性，点击一次文章后，布局可能会混乱，判断不准是否在阅读页面）
 */
function reLaunchAndSwitchToReadTabBar() {

}

/**
 * 获得所有当前可见的文章
 */
function getVisibleArtileArray() {

    var allView = className("android.view.View").find();
    // toastLog(idMatches("gerenzhongxin").findOne().desc().length)

    var cleanViewArray = new Array();
    for (let index = 0; index < allView.length; index++) {
        var item = allView[index];

        if (item == null) {
            continue;
        }
        if (item.desc() == null) {
            continue;
        }

        // 过滤发布时间 与内容小于5的
        if (item.desc().length <= 5 || (item.desc().indexOf(APP_NAME) != -1)) {
            continue;
        }
        // 过滤一些无关
        if (item.desc().indexOf("上拉显示更多") != -1) {
            continue;
        }
        if (item.desc().indexOf("广告") != -1) {
            continue;
        }
        if (item.desc().indexOf("正在加载") != -1) {
            continue;
        }

        // 去除广告
        if (item.parent()) {
            if (item.parent().childCount() > 4) {
                if (item.parent().child(4).desc() == "广告") {
                    continue;
                }
            }
        }

        if (!checkIsvisible(item.bounds())) {
            continue;
        }

        if (!checkIfVisibleArticleItem(item.bounds())) {
            continue;
        }

        cleanViewArray.push(item);
    }
    return cleanViewArray;
}

// 刷新布局, 此方法只有webView布局混乱后，才有效果,其实就是点击文章的分享按钮
function refreshLayout() {
    // 进入一篇文章，并点击分享按钮
    // 高一定是比宽大的
    var realHeight = device.height;
    var realWidth = device.width;

    if (realHeight < realWidth) {
        realHeight = device.width;
        realWidth = device.height;
    }

    var detail = desc("任务详情").findOne(3000);
    if (!detail) {
        toastLog("不在文章页");
        // 判断是否在广告页，如果在广告页才需要back
        if (checkIfAdPage()) {
            back();
        }
        // todo 也有可能是刚才的点击，没有进入到文章

        sleep(2000);
        if (!ifReadPage()) {
            switchToReadTabBar();
        }
        return false;
    }
    //  log(detail.bounds().right)
    // todo shareBtnY 应该是一进入文章页，就获取，要不然不准确
    var shareBtnY = detail.bounds().centerY();
    // var shareBtn =detail.parent().child(1);
    var shareBtnX = realWidth - (realWidth - detail.bounds().right) / 2;

    log("分享按钮位置：" + shareBtnX + ":" + shareBtnY);
    // Tap(shareBtnX, shareBtnY);
    Tap(shareBtnX, 98);
    sleep(1000);

    var cancelBtn = text("取消").findOne(5000);
    // while(!refresh){

    // }
    if (cancelBtn) {
        clickBtnByBoundsCenter(cancelBtn);
        toastLog("恢复布局成功");
        sleep(2000);
        return true;
    } else {
        toastLog("点击分享失败");
        return false;
    }
}


function main() {
    //声明模式
    auto.waitFor();
    // setScreenMetrics(720, 1280);
    checkIfHeightAndWidthNormal();

    // 启动app
    launch(appPackageName);
    initStorage();
    // sleep(8000)
    // 查看是否已登录账号
    // if (!ifLogined()) {
    //     toastLog("未登录，请先登录账号");
    //     // exit();
    // }
    // 切换到阅读tabbar
    switchToReadTabBar();

    readArticleCount = storage.get("readArticleCount");
    toastLog("已阅读文章" + readArticleCount);
    if (readArticleCount == null) {
        readArticleCount = 0;
    }
    while (readArticleCount < needReadArticleNum) {
        if (!ifReadPage()) {
            switchToReadTabBar();
            continue;
        }
        readArticleCount = storage.get("readArticleCount");
        toastLog("已阅读文章" + readArticleCount);
        sleep(2000);

        // 查找可见文章
        var visibleArticleArray = getVisibleArtileArray();
        log("可视文章" + visibleArticleArray);
        if (visibleArticleArray == null || visibleArticleArray.length == 0) {
            toastLog("找不到文章");
            sleep(3000);
        }
        // 获取没有读过的文章
        var needReadArray = getUnReadedArticleArrayToday(visibleArticleArray);
        log("uuuuuuuu")
        log(needReadArray);
        for (var index = 0; index < needReadArray.length; index++) {
            var element = needReadArray[index];
            log("++++++++++")
            log(index + "\n" + element);
            // clickAnArticle();
            clickAnArticleByBounds(element);
            log("阅读文章：" + element);
            sleep(3000);
            // 通过错误次数自旋
            var errorCount = 0;
            while (!finishReadAnArticle() || errorCount > 2) {
                // 更新阅读过的文章
                markReaded(element.desc());
                readArticleCount += 1;
                storage.put("readArticleCount", readArticleCount);

                sleep(1000);

                // 先刷新布局
                var refreshLayoutFlag = false;
                while (!refreshLayoutFlag && errorCount < 2) {
                    errorCount++;
                    if (refreshLayout()) {
                        refreshLayoutFlag = true;
                    }
                    sleep(1000);
                }

                // 返回
                back();
                // backToReadTabBar();

                sleep(2000);
            }

            toastLog("已阅读文章" + readArticleCount);
        }
        // 完成或者没找到，都下拉
        simulateScorllDown();
        sleep(2000);

        // 刷新布局
        var refreshLayoutFlag = false;

        clickAnArticleByBounds(getVisibleArtileArray()[0]);

        log("点击文章来刷新布局")
        // 通过错误次数自旋
        var errorCount = 0;
        while (!refreshLayoutFlag) {
            errorCount++;
            if (refreshLayout()) {
                refreshLayoutFlag = true;
                sleep(1000);
                back();
            }
            if (errorCount > 2) {
                refreshLayoutFlag = true;
            }
            sleep(1000);
            simulateScorllDown();
            sleep(2000);
            clickAnArticleByBounds(getVisibleArtileArray()[0]);
        }
    }

}

main();
// log(getVisibleArtileArray())


toastLog(false && false)
